package com.mutouren.common.nosql;

import java.util.HashMap;
import java.util.Map;

import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.MongoClient;

public class MongoSource {
	
	private static Map<String, MongoClient> mapClient = new HashMap<String, MongoClient>();
	private static Map<String, MongoConfig> mapDB = new HashMap<String, MongoConfig>();
	
	public static DB getDB(String database) {
		return getMongoClient(database).getDB(getRealDBName(database));
	}
	
	public static DBCollection getDBCollection(String database, String colName) {
		return getMongoClient(database).getDB(getRealDBName(database)).getCollection(colName);
	}
	
	private synchronized static MongoClient getMongoClient(String database) {
		
		if(mapDB.containsKey(database)) {
			String clientName = mapDB.get(database).getClientName();
			if(mapClient.containsKey(clientName)) {
				return mapClient.get(clientName);
			}
		}
		
		MongoConfig config = new MongoConfig(database);
		if(mapClient.containsKey(config.getClientName())) {
			mapDB.put(database, config);
			return mapClient.get(config.getClientName());
		}
				
		MongoClient client = new MongoClient(config.getListAddress(), config.getMongoOptions());
		mapDB.put(database, config);
		mapClient.put(config.getClientName(), client);
		
		return client;
	}
	
	private synchronized static String getRealDBName(String database) {
		return mapDB.get(database).getDatabase();
	}
	
}
